package com.self.campussecondhandmarket.controller.user;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.self.campussecondhandmarket.common.BaseContext;
import com.self.campussecondhandmarket.entity.domain.Goods;
import com.self.campussecondhandmarket.entity.domain.Orders;
import com.self.campussecondhandmarket.entity.domain.User;
import com.self.campussecondhandmarket.entity.request.goods.Action;
import com.self.campussecondhandmarket.entity.request.goods.MyOrders;
import com.self.campussecondhandmarket.entity.request.orders.*;
import com.self.campussecondhandmarket.entity.response.orders.AllOrders;
import com.self.campussecondhandmarket.entity.response.orders.DetailResp;
import com.self.campussecondhandmarket.entity.response.orders.MyOrdersResp;
import com.self.campussecondhandmarket.entity.response.orders.OrdersListResp;
import com.self.campussecondhandmarket.enums.ActionEnum;
import com.self.campussecondhandmarket.enums.OrdersStatusEnum;
import com.self.campussecondhandmarket.enums.PickEnum;
import com.self.campussecondhandmarket.resp.Result;
import com.self.campussecondhandmarket.service.GoodsService;
import com.self.campussecondhandmarket.service.OrdersService;
import com.self.campussecondhandmarket.service.UserService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Vincent
 * <p> DateTime: 2024/4/13 11:19
 * <p> Description: 订单视图
 * <p>
 **/
@Slf4j
@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "http://localhost:9999", allowCredentials = "true")
public class OrdersController {
	
	@Autowired
	UserService userService;
	
	@Autowired
	OrdersService ordersService;
	
	@Autowired
	GoodsService goodsService;
	
	/**
	 * 创建订单
	 */
	@PostMapping("/createOrders")
	public Result<String> createOrders(@RequestBody @NonNull CreateOrders dto) {
		log.info("进入 orders ---> createOrders");
		return ordersService.createOrders(dto);
	}
	
	/**
	 * 查看订单列表
	 */
	@PostMapping("/list")
	public Result list(@RequestBody @NonNull OrderList dto) {
		log.info("进入 orders ---> list");
		List<Orders> list = ordersService.list(Wrappers.<Orders>lambdaQuery()
				.eq(Orders::getUserId, BaseContext.getId())
				.eq(Orders::getStatus, dto.getStatus())
				.eq(Orders::getAction, dto.getAction())
		);
		List<OrdersListResp> vo = list.stream().map(o -> {
			User user = userService.getById(o.getUserId());
			Goods good = goodsService.getById(o.getGoodsId());
			OrdersListResp ordersListResp = new OrdersListResp();
			BeanUtils.copyProperties(o, ordersListResp);
			ordersListResp.setPhone(user.getPhone());
			ordersListResp.setName(good.getName());
			return ordersListResp;
		}).toList();
		
		return Result.success(vo);
	}
	
	/**
	 * 修改订单
	 */
	@PostMapping("/action")
	public Result<String> action(@RequestBody @NonNull Action dto) {
		ordersService.update(Wrappers.<Orders>lambdaUpdate()
				.set(Orders::getAction, dto.getAction())
				.eq(Orders::getId, dto.getId())
		);
		return Result.success("订单修改成功");
	}
	
	/**
	 * 查看我的订单
	 */
	@PostMapping("/myOrder")
	public Result<List<MyOrdersResp>> getMyOrders(@RequestBody MyOrders dto) {
		List<Orders> list = ordersService.list(Wrappers.<Orders>lambdaQuery()
				.eq(Orders::getStatus, dto.getOrderStatus())
				.eq(Orders::getUserId, BaseContext.getId())
		);
		
		List<MyOrdersResp> res = list.stream().map(o -> {
			Goods goods = goodsService.getById(o.getGoodsId());
			User user = userService.getById(goods.getUserId());
			MyOrdersResp vo = new MyOrdersResp();
			vo.setGoodsId(o.getGoodsId());
			vo.setAddress(o.getAddress());
			vo.setPrice(o.getPrice());
			vo.setQuantity(o.getQuantity());
			vo.setCreateTime(o.getCreateTime());
			String img = goods.getImg();
			List<String> imgs = new ArrayList<>();
			if (img != null) {
				imgs = JSON.parseArray(img, String.class);
			}
			vo.setImg(imgs.get(0));
			vo.setName(goods.getName());
			vo.setSellerPhone(user.getPhone());
			vo.setStatus(o.getStatus());
			vo.setId(o.getId());
			return vo;
		}).toList();
		
		return Result.success(res);
	}
	
	/**
	 * 取消订单
	 */
	@PostMapping("/cancel")
	public Result<String> cancel(@RequestBody @NonNull Cancel dto) {
		if (dto.getGoodsId() == null
				|| dto.getStatus() == null
				|| dto.getOrdersId() == null
				|| dto.getQuantity() == null) {
			return Result.error("参数异常");
		}
		return ordersService.cancel(dto);
	}
	
	/**
	 * 收货
	 */
	@PostMapping("/receiving")
	public Result<String> Receiving(@RequestBody Receiving dto) {
		if (dto.getId() == null
				|| dto.getStatus() == null) {
			return Result.error("参数异常");
		}
		ordersService.update(Wrappers.<Orders>lambdaUpdate()
				.set(Orders::getStatus, dto.getStatus())
				.eq(Orders::getId, dto.getId())
		);
		return Result.success("收货成功");
	}
	
	/**
	 * 查看订单详情
	 */
	@PostMapping("/detail")
	public Result detail(@RequestBody @NonNull Detail dto) {
		DetailResp vo = new DetailResp();
		if (dto.getId() == null) {
			return Result.error("参数异常");
		}
		Orders orders = ordersService.getById(dto.getId());
		Goods goods = goodsService.getById(orders.getGoodsId());
		vo.setPrice(orders.getPrice());
		vo.setName(goods.getName());
		vo.setMsg(JSON.parseArray(goods.getImg(), String.class).get(0));
		return Result.success(vo);
	}
	
	@PostMapping("/admin/all")
	public Result all() {
		List<AllOrders> list = ordersService.list().stream().map(o -> {
			User user = userService.getById(o.getUserId());
			AllOrders vo = new AllOrders();
			BeanUtils.copyProperties(o, vo);
			vo.setStatus(OrdersStatusEnum.getValue(o.getStatus()));
			vo.setPick(PickEnum.getDesc(o.getPick()));
			vo.setName(user.getName());
			vo.setPhone(user.getPhone());
			vo.setAction(ActionEnum.getDesc(o.getAction()));
			return vo;
		}).toList();
		return Result.success(list);
	}
	
	@PostMapping("/admin/edit")
	public Result edit(@RequestBody @NonNull AllOrders dto) {
		
		ordersService.update(Wrappers.<Orders>lambdaUpdate()
				.eq(Orders::getId, dto.getId())
				.set(Orders::getPick, PickEnum.getPick(dto.getPick()))
				.set(Orders::getStatus, OrdersStatusEnum.getStatus(dto.getStatus()))
				.set(Orders::getAddress, dto.getAddress())
				.set(Orders::getRemark, dto.getRemark())
				.set(Orders::getAction, ActionEnum.getAction(dto.getAction())));
		return Result.success("修改成功");
	}
	
	@PostMapping("/admin/add")
	public Result add(@RequestBody @NonNull AllOrders dto) {
		User user = userService.getById(dto.getUserId());
		if (user == null) {
			return Result.error("用户不存在");
		}
		Goods goods = goodsService.getById(dto.getGoodsId());
		if (goods == null) {
			return Result.error("商品不存在");
		}
		Orders orders = new Orders();
		BeanUtils.copyProperties(dto, orders);
		orders.setPick(PickEnum.getPick(dto.getPick()));
		orders.setOrdersNo(System.currentTimeMillis());
		orders.setPrice(goods.getPrice());
		orders.setTotalPrice(dto.getQuantity() * goods.getPrice());
		ordersService.save(orders);
		return Result.success();
	}
	
	@PostMapping("/admin/filter")
	public Result filter(@RequestBody AllOrders dto) {
		List<Integer> user = new ArrayList<>();
		
		if (dto.getPhone() != null)
			user = userService.list(Wrappers.<User>lambdaQuery().eq(User::getPhone, dto.getPhone())).stream().map(User::getId).toList();
		List<AllOrders> list = ordersService.list(Wrappers.<Orders>lambdaQuery()
				.eq(dto.getAction() != null, Orders::getAction, dto.getAction())
				.eq(dto.getOrdersNo() != null, Orders::getOrdersNo, dto.getOrdersNo())
				.eq(dto.getPick() != null, Orders::getPick, dto.getPick())
				.in(!user.isEmpty(), Orders::getUserId, user)
				.eq(dto.getStatus() != null, Orders::getStatus, dto.getStatus())
		).stream().map(o -> {
			User temp = userService.getById(o.getUserId());
			AllOrders vo = new AllOrders();
			BeanUtils.copyProperties(o, vo);
			vo.setStatus(OrdersStatusEnum.getValue(o.getStatus()));
			vo.setPick(PickEnum.getDesc(o.getPick()));
			vo.setName(temp.getName());
			vo.setPhone(temp.getPhone());
			vo.setAction(ActionEnum.getDesc(o.getAction()));
			return vo;
		}).toList();
		return Result.success(list);
		
	}
}
